package com.example.smartlearning.service.impl;

import com.example.smartlearning.entity.ResultEntity;
import com.example.smartlearning.service.MailService;
import com.example.smartlearning.tool.JSONTool;
import com.example.smartlearning.tool.SmsUtil;
import com.example.smartlearning.tool.VerCodeGenerateTool;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;


@Service
public class MailServiceImpl implements MailService {

    private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);//日志。getLogger需要传入当前的类名
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private JavaMailSenderImpl javaMailSender;

    @Value("${spring.mail.username}")
    private String sendMailer;

    @Resource
    SmsUtil smsUtil;

    @Resource
    VerCodeGenerateTool verCodeGenerateTool;

    @Override
    public String sendRoundTextMailMessage(String to) {
        ResultEntity resultEntity = new ResultEntity(null, null, null);
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(to.split(","));
            //邮件主题
//            mimeMessageHelper.setSubject(subject);
            String code = verCodeGenerateTool.generateRandomString();
            //生成随机的验证码
            String text = "【智能享学】验证码" + code + "，您正在进行身份验证，该验证码5分钟内有效，请勿泄露于他人。";
            //邮件内容
            mimeMessageHelper.setText(text);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            //将验证码缓存到redis
            stringRedisTemplate.opsForValue().set(to, code, 5, TimeUnit.MINUTES);//加入验证码到redis中 设置过期时间为5分钟
            System.out.println(stringRedisTemplate.opsForValue().get(to));
            resultEntity.setCode(200);
            resultEntity.setMsg("发送成功");

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getLocalizedMessage());
            resultEntity.setCode(900);
            resultEntity.setMsg("发送失败");
        }
        return JSONTool.getJsonTool().toJson(resultEntity);
    }

    /**
     * 阿里云短信发送
     *
     * @param phone 手机号
     * @return 返回
     */
    @Override
    public String SendSms(String phone) {
        ResultEntity resultEntity = new ResultEntity(null, null, null);
        try {
            String code = verCodeGenerateTool.generateRandomString();
//            String code = "123456";
            HashMap<String, Object> templateParam = new HashMap<>();
            templateParam.put("code", code);
            smsUtil.sendSms(phone, templateParam);
            stringRedisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);//加入验证码到redis中 设置过期时间为5分钟
            resultEntity.setCode(200);
            resultEntity.setMsg("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getLocalizedMessage());
            resultEntity.setCode(900);
            resultEntity.setMsg("发送失败");
        }
        return JSONTool.getJsonTool().toJson(resultEntity);
    }

    /**
     * 验证验证码
     * 验证码使用场景:
     * 1.当登录ip发生改变的时候强制使用验证码进行登录
     * 2.用户忘记密码的时候用验证码进行登录
     *
     * @param account 账号
     * @param code    验证码
     * @return 返回
     */
    @Override
    public String checkCode(String account, String code) {
        //不管是邮箱验证还是手机号验证 account都会上传到redis中 所以根据这个直接取值就行
        String codeInRedis = stringRedisTemplate.opsForValue().get(account);
        ResultEntity resultEntity = new ResultEntity(null, null, null);
        if (codeInRedis == null || !codeInRedis.equals(code)) {
            resultEntity.setCode(900);
            resultEntity.setMsg("验证码错误");
        } else {
            resultEntity.setCode(200);
            resultEntity.setMsg("验证通过");
            stringRedisTemplate.delete(account);//从redis中删除

        }
        return JSONTool.getJsonTool().toJson(resultEntity);
    }
}
